package com.lucenex.core;

import java.io.Closeable;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.lucene.index.IndexWriter;

import com.lucenex.util.OpenLuceneSource;

/**
 * 核心数据源控制 (单利模式)
 * @author zxw
 *
 */
public class LuceneDataSource implements Closeable{
	
	/**
	 * 数据源 MAP 集合
	 */
	private Map<String, LuceneXConfig> dataSource;

	/**
	 * 多数据源 线程锁
	 */
	private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
	
	
	static LuceneDataSource kit = new LuceneDataSource();
	
	public static synchronized LuceneDataSource build() {
		if(kit.dataSource == null) {
			kit.dataSource = new HashMap<String, LuceneXConfig>();
		}
		return kit;
	}
	
	/**
	 * 获取一个源
	 * @param key
	 * @return
	 * @throws IOException 
	 */
	public LuceneXConfig getDataSource(String key) throws IOException {
		LuceneXConfig luceneXConfig = OpenLuceneSource.builder().build().mergeSource(key.split(","));
		if(luceneXConfig != null) {
			return luceneXConfig;
		}
		return this.dataSource.get(key);
	}
	
	/**
	 * 添加一个源
	 * @param key
	 * @param luceneXConfig
	 */
	public void setDataSource(String key,LuceneXConfig luceneXConfig) {
		this.dataSource.put(key, luceneXConfig);
	}
	
	/**
	 * 添加当前线程 数据源 Key
	 * @param type
	 */
	public static void setDatabaseType(String type) {
		contextHolder.set(type);
	}
	
	/**
	 * 获取当前线程 数据源 
	 * @return
	 */
	public static String getDatabaseType() {
		return contextHolder.get();
	}

	/**
	 * 清理当前线程 数据源 
	 */
	public static void clearDatabaseType() {
		contextHolder.remove();
	}

	/**
	 * 清理资源
	 */
	@Override
	public void close(){
		if(this.dataSource != null) {
			Set<Entry<String,LuceneXConfig>> set = this.dataSource.entrySet();
			for (Entry<String, LuceneXConfig> entry : set) {
				LuceneXConfig conf = entry.getValue();
				//清理写源
				IndexWriter writer = conf.getWriter();
				try {
					writer.commit();
					writer.flush();
				} catch (Exception e) {
				}finally {
					try {
						writer.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			}
			this.dataSource.clear();
		}
		clearDatabaseType();
	}
	
	/**
	 * 手动提交工作
	 * @throws IOException
	 */
	public void submit() throws IOException {
		if(this.dataSource != null) {
			Set<Entry<String,LuceneXConfig>> set = this.dataSource.entrySet();
			for (Entry<String, LuceneXConfig> entry : set) {
				LuceneXConfig conf = entry.getValue();
				//清理写源
				IndexWriter writer = conf.getWriter();
				writer.commit();
				writer.flush();
			}
		}
	}

}
